// API基础URL
const API_BASE_URL = 'https://api.jobapp.example.com/v1';

// 默认请求选项
const defaultOptions = {
    headers: {
        'Content-Type': 'application/json'
    }
};

// 处理API响应
async function handleResponse(response) {
    const data = await response.json();
    
    if (!response.ok) {
        const error = data.message || response.statusText;
        throw new Error(error);
    }
    
    return data;
}

// 添加认证令牌到请求头
function addAuthHeader(options = {}) {
    const token = localStorage.getItem('auth_token');
    if (!token) return options;
    
    const headers = {
        ...options.headers,
        'Authorization': `Bearer ${token}`
    };
    
    return {
        ...options,
        headers
    };
}

// API服务对象
const apiService = {
    // 获取附近的工作
    async getNearbyJobs(latitude, longitude, radius = 10, filters = {}) {
        const queryParams = new URLSearchParams({
            lat: latitude,
            lng: longitude,
            radius,
            ...filters
        });
        
        const response = await fetch(`${API_BASE_URL}/jobs/nearby?${queryParams}`, 
            addAuthHeader(defaultOptions)
        );
        
        return handleResponse(response);
    },
    
    // 获取最新的工作
    async getLatestJobs(page = 1, limit = 10, filters = {}) {
        const queryParams = new URLSearchParams({
            page,
            limit,
            ...filters
        });
        
        const response = await fetch(`${API_BASE_URL}/jobs/latest?${queryParams}`, 
            addAuthHeader(defaultOptions)
        );
        
        return handleResponse(response);
    },
    
    // 搜索工作
    async searchJobs(keyword, filters = {}, page = 1, limit = 10) {
        const queryParams = new URLSearchParams({
            keyword,
            page,
            limit,
            ...filters
        });
        
        const response = await fetch(`${API_BASE_URL}/jobs/search?${queryParams}`, 
            addAuthHeader(defaultOptions)
        );
        
        return handleResponse(response);
    },
    
    // 获取工作详情
    async getJobDetail(jobId) {
        const response = await fetch(`${API_BASE_URL}/jobs/${jobId}`, 
            addAuthHeader(defaultOptions)
        );
        
        return handleResponse(response);
    },
    
    // 用户登录
    async login(email, password) {
        const response = await fetch(`${API_BASE_URL}/auth/login`, {
            ...defaultOptions,
            method: 'POST',
            body: JSON.stringify({ email, password })
        });
        
        const data = await handleResponse(response);
        
        // 保存认证令牌
        if (data.token) {
            localStorage.setItem('auth_token', data.token);
            localStorage.setItem('user_id', data.user.id);
        }
        
        return data;
    },
    
    // 用户注册
    async register(name, email, password) {
        const response = await fetch(`${API_BASE_URL}/auth/register`, {
            ...defaultOptions,
            method: 'POST',
            body: JSON.stringify({ name, email, password })
        });
        
        const data = await handleResponse(response);
        
        // 保存认证令牌
        if (data.token) {
            localStorage.setItem('auth_token', data.token);
            localStorage.setItem('user_id', data.user.id);
        }
        
        return data;
    },
    
    // 获取用户信息
    async getUserProfile() {
        const response = await fetch(`${API_BASE_URL}/user/profile`, 
            addAuthHeader(defaultOptions)
        );
        
        return handleResponse(response);
    },
    
    // 更新用户信息
    async updateUserProfile(profileData) {
        const response = await fetch(`${API_BASE_URL}/user/profile`, {
            ...addAuthHeader(defaultOptions),
            method: 'PUT',
            body: JSON.stringify(profileData)
        });
        
        return handleResponse(response);
    },
    
    // 获取用户简历
    async getUserResumes() {
        const response = await fetch(`${API_BASE_URL}/user/resumes`, 
            addAuthHeader(defaultOptions)
        );
        
        return handleResponse(response);
    },
    
    // 上传简历
    async uploadResume(formData) {
        const options = addAuthHeader({
            method: 'POST',
            body: formData
        });
        
        // 删除Content-Type头，让浏览器自动设置
        delete options.headers['Content-Type'];
        
        const response = await fetch(`${API_BASE_URL}/user/resumes`, options);
        
        return handleResponse(response);
    },
    
    // 投递简历
    async applyForJob(jobId, resumeId) {
        const response = await fetch(`${API_BASE_URL}/jobs/${jobId}/apply`, {
            ...addAuthHeader(defaultOptions),
            method: 'POST',
            body: JSON.stringify({ resumeId })
        });
        
        return handleResponse(response);
    },
    
    // 获取用户的申请记录
    async getApplications(page = 1, limit = 10) {
        const queryParams = new URLSearchParams({
            page,
            limit
        });
        
        const response = await fetch(`${API_BASE_URL}/user/applications?${queryParams}`, 
            addAuthHeader(defaultOptions)
        );
        
        return handleResponse(response);
    },
    
    // 收藏职位
    async favoriteJob(jobId) {
        const response = await fetch(`${API_BASE_URL}/jobs/${jobId}/favorite`, {
            ...addAuthHeader(defaultOptions),
            method: 'POST'
        });
        
        return handleResponse(response);
    },
    
    // 取消收藏职位
    async unfavoriteJob(jobId) {
        const response = await fetch(`${API_BASE_URL}/jobs/${jobId}/favorite`, {
            ...addAuthHeader(defaultOptions),
            method: 'DELETE'
        });
        
        return handleResponse(response);
    },
    
    // 获取收藏的职位
    async getFavorites(page = 1, limit = 10) {
        const queryParams = new URLSearchParams({
            page,
            limit
        });
        
        const response = await fetch(`${API_BASE_URL}/user/favorites?${queryParams}`, 
            addAuthHeader(defaultOptions)
        );
        
        return handleResponse(response);
    },
    
    // 检查用户是否已登录
    isLoggedIn() {
        return !!localStorage.getItem('auth_token');
    },
    
    // 登出
    logout() {
        localStorage.removeItem('auth_token');
        localStorage.removeItem('user_id');
    }
};

// 为了方便调试，将API服务挂载到全局对象
window.apiService = apiService; 